package com.napenalki.toto.service.impl;

import static com.napenalki.toto.service.impl.EntityValidationHelper.validateEntity;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.napenalki.toto.dao.UserDao;
import com.napenalki.toto.domain.User;
import com.napenalki.toto.service.IllegalEntryException;
import com.napenalki.toto.service.UserService;

@Service
public class UserServiceImpl implements UserService {

    private UserDao dao;
    
    @Autowired
    public UserServiceImpl(UserDao dao) {
        this.dao = dao;
    }

    @Override
    public User addUser(User user) {
        
        validateEntity(user);        
        
        User userx = dao.findUserByName(user.getUserName());
        
        if (userx == null) {
            return dao.addUser(user);
        } else {
            return userx;
        }
        
    }
    
    @Override
    public User findUserByName(String userName) {
        if (userName == null) {
            throw new IllegalEntryException("User name cannot be null");
        }
        return dao.findUserByName(userName);
    }

    @Override
    public List<User> findAllUsers() {
        return dao.findAllUsers();
    }
    
    @Override
    public List<User> getUserRanking() {
        return dao.findUsersOrderedByPoints();
    }
    
    @Override
    public User login(String userName, String password) {
        if (userName == null || password == null) {
            throw new IllegalEntryException("User name or password cannot be null");
        }
        
        User user = dao.findUserByName(userName);
        
        if (user != null && user.getPassword().equals(password)) {
            return user;
        }
        
        return null;
    }
    
    @Override
    public User updateUser(User user) {
        validateEntity(user);
        return dao.updateUser(user);
    }
    
    @Override
    public void deleteUser(User user) {
        if (user == null) {
            return;
        }
        dao.deleteUser(user);
    }

}
